package com.xujl.clock;

import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.xujl.task.RxExecutor;
import com.xujl.task.RxHelper;
import com.xujl.task.RxLife;
import com.xujl.task.RxLifeList;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, OnItemClickListener {
    private static final String TAG = "MainActivity";
    private TextView mTimeTv;
    private RecyclerView mRv;
    private List<Bean> mList = new ArrayList<>();
    private RxLifeList mLifeList = new RxLifeList();
    private SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
    private static final int MODE_STOP = 0;
    private static final int MODE_END_1 = 1;//将要结束
    private static final int MODE_END = 2;//已结束
    private static final int MODE_RUN = 2;//进行中
    private int mode = MODE_STOP;
    private static final long LAST_TIME = 5 * 60 * 1000;//临近提醒时间
    private static final long LAST_TIME_2 = 4 * 60 * 1000;//临近提醒时间
    private BaseQuickAdapter<Bean, BaseViewHolder> mAdapter = new BaseQuickAdapter<Bean, BaseViewHolder>(R.layout.item_time, mList) {
        @Override
        protected void convert (BaseViewHolder holder, Bean bean) {
            holder.setText(R.id.tv_time, bean.getTitle())
                    .setBackgroundResource(R.id.tv_time, bean.isChecked() ? R.drawable.time_bg_p : R.drawable.time_bg);
        }
    };

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        mTimeTv = findViewById(R.id.tv_time);
        mRv = findViewById(R.id.rv);
        findViewById(R.id.btn_cancel).setOnClickListener(this);
        mList.add(new Bean(1L));
        mList.add(new Bean(6L));
        mList.add(new Bean(30L));
        mList.add(new Bean(40L));
        mList.add(new Bean(45L));
        mList.add(new Bean(50L));
        mList.add(new Bean(60L));
        mList.add(new Bean(80L));
        mList.add(new Bean(90L));
        mList.add(new Bean(100L));
        mList.add(new Bean(120L));

        mRv.setLayoutManager(new GridLayoutManager(this, 2));
        mAdapter.setOnItemClickListener(this);
        mRv.setAdapter(mAdapter);
    }

    @Override
    public void onClick (View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setTitle("提醒");
        builder.setMessage("确定要取消吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick (DialogInterface dialog, int which) {
                dialog.dismiss();
                reset();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick (DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    private void reset () {
        stopMusic();
        mLifeList.onDestroy();
        mTimeTv.setText("00:00:00");
        for (Bean bean : mList) {
            bean.setChecked(false);
        }
        mAdapter.notifyDataSetChanged();
    }

    private void start (final Bean bean) {
        mLifeList.onDestroy();
        mode = MODE_RUN;
        bean.setEndTime(System.currentTimeMillis() + bean.getTime());
        RxExecutor.getInstance()
                .executeTask(new RxHelper.RecycleTask(true, 500, -1) {
                    @Override
                    public void count (int count) {
                        if (mode == MODE_STOP) {
                            return;
                        }
                        final long time = bean.getEndTime() - System.currentTimeMillis();
                        if (time < LAST_TIME && time > LAST_TIME_2 && mode != MODE_END_1) {
                            mode = MODE_END_1;
                            playEnd1();
                        }
                        if (time <= 0) {
                            mode = MODE_STOP;
                            playEnd2();
                            reset();
                            return;
                        }
                        mTimeTv.setText(formatter.format(time));
                    }

                    @Override
                    public void bindLife (RxLife rxLife) {
                        super.bindLife(rxLife);
                        mLifeList.add(rxLife);
                    }
                });
    }

    @Override
    protected void onResume () {
        super.onResume();
        if (mode == MODE_STOP) {
            reset();
        }
    }

    @Override
    public void onItemClick (@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        for (int i = 0; i < mList.size(); i++) {
            mList.get(i).setChecked(i == position);
        }
        start(mList.get(position));
        mAdapter.notifyDataSetChanged();
    }


    private void playEnd1 () {
        Log.i(TAG, "playEnd1");
        playMusic(R.raw.notice);
    }

    private void playEnd2 () {
        Log.i(TAG, "playEnd2");
        playMusic(R.raw.notice2);
        if (mRingPlayer != null) {
            mRingPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion (MediaPlayer mp) {
                    playEnd3();
                    mRingPlayer.setOnCompletionListener(null);
                }
            });
        }
    }

    private void playEnd3 () {
        Log.i(TAG, "playEnd3");
        playMusic(R.raw.music);
    }

    private MediaPlayer mRingPlayer;

    private void playMusic (int res) {
        stopMusic();
        mRingPlayer = MediaPlayer.create(this, res);
        mRingPlayer.setLooping(false);
        mRingPlayer.start();
    }

    private void stopMusic () {
        if (mRingPlayer != null) {
            mRingPlayer.stop();
            mRingPlayer.release();
            mRingPlayer = null;
        }
    }

}
